import formInfo from '@ohos.app.form.formInfo';
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formProvider from '@ohos.app.form.formProvider';
import request from '@ohos.request';
import dataStorage from '@ohos.data.storage';
import fs from '@ohos.file.fs'

const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store";
const FORM_PARAM_IDENTITY_KEY = "ohos.extra.param.key.form_identity";
const FORM_PARAM_NAME_KEY = "ohos.extra.param.key.form_name";
const FORM_PARAM_TEMPORARY_KEY = "ohos.extra.param.key.form_temporary";

function padZero(num: number) {
  // trans num to string and pad 0
  if (num < 10) {
    return `0${num}`;
  } else {
    return num.toString();
  }
}

function getTime() {
  const date = new Date();
  const years = padZero(date.getFullYear());
  const month = padZero(date.getMonth() + 1);
  const days = padZero(date.getDate());
  const hours = padZero(date.getHours());
  const minutes = padZero(date.getMinutes());
  const seconds = padZero(date.getSeconds());
  return years + "年" + ` ${month}` + "月" + days + "日"
}

async function updateForm(formId: string) {
  let formInfoDefault = {
    "formName": "",
    "tempFlag": false,
    "updateCount": 0
  ,
    "time": getTime()
  };
  try {
    const storage = await dataStorage.getStorage(DATA_STORAGE_PATH);
    // get form info
    const data = await storage.get(formId, JSON.stringify(formInfoDefault));

    const formInfo = JSON.parse(data.toString());
    formInfo.updateCount = formInfo.updateCount + 1;

    let obj = {

      "time": getTime()
    };
    let formData = formBindingData.createFormBindingData(obj);
    formProvider.updateForm(formId, formData).catch((err) => {

    });

    // update form info
    await storage.put(formId, JSON.stringify(formInfo));

    await storage.flush();
  } catch (err) {

  }
}


export default class EntryFormAbility extends FormExtensionAbility {
  onAddForm(want) {

    // Called to return a FormBindingData object.
    let obj = {
      'time': getTime()
    };
    let formData: formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
    return formData;
  }

  onCastToNormalForm(formId) {
    // Called when the form provider is notified that a temporary form is successfully
    // converted to a normal form.
  }

  onUpdateForm(formId) {

    updateForm(formId)
    // upimg(formId)
    // Called to notify the form provider to update a specified form.
  }

  onChangeFormVisibility(newStatus) {
    // Called when the form provider receives form events from the system.
  }


  onFormEvent(formId, message) {

    // upimg(formId)
    let formInfo = formBindingData.createFormBindingData({
      'text': '刷新中...'
    })
    formProvider.updateForm(formId, formInfo)
    // 注意：FormExtensionAbility在触发生命周期回调时被拉起，仅能在后台存在5秒
    // 建议下载能快速下载完成的小文件，如在5秒内未下载完成，则此次网络图片无法刷新至卡片页面上
    let netFile = 'https://xiuxiupro-material-center.meitudata.com/poster/8c98b88845630b4afc694e90ca81daa2.png'; // 需要在此处使用真实的网络图片下载链接
    let tempDir = this.context.getApplicationContext().tempDir;
    let fileName = 'file' + Date.now();
    let tmpFile = tempDir + '/' + fileName;
    request.downloadFile(this.context, {
      url: netFile, filePath: tmpFile, enableMetered: true, enableRoaming: true
    }).then((task) => {
      task.on('complete', function callback() {
        console.info('ArkTSCard download complete:' + tmpFile);
        let file;
        try {
          file = fs.openSync(tmpFile);
        } catch (e) {
          console.error(`openSync failed: ${JSON.stringify(e)}`);
        }
        let fileInfo = {};
        fileInfo[fileName] = file.fd;
        let formData = {
          'text': 'Image:' + fileName,
          'imgName': fileName,
          'formImages': fileInfo,
          'loaded': true,
          'time': getTime()
        };
        let formInfo = formBindingData.createFormBindingData(formData)
        formProvider.updateForm(formId, formInfo).then((data) => {
          console.info('FormAbility updateForm success.' + JSON.stringify(data));
        }).catch((error) => {
          console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
        })
      })
      task.on('fail', function callBack(err) {
        console.info('ArkTSCard download task failed. Cause:' + err);
        let formInfo = formBindingData.createFormBindingData({
          'text': '刷新失败'
        })
        formProvider.updateForm(formId, formInfo)
      });
    }).catch((err) => {
      console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
    });
  }

  onRemoveForm(formId) {
    // Called to notify the form provider that a specified form has been destroyed.
  }

  onAcquireFormState(want) {
    // Called to return a {@link FormState} object.
    return formInfo.FormState.READY;
  }
};